﻿using DotNetty.Buffers;
using QQ.Client;
using QQ.Codecs;
using QQ.Utils;
using static QQ.Codecs.DotNettyByteBufferExtensions.LengthType;
using static QQ.Utils.MiscHelper;

namespace QQ.Packet.Request.TLV
{
    public class TLV0x106 : IRequest
    {
        public uint uin { get; set; }
        public string password { get; set; }
        public LoginType loginType { get; set; }
        private long salt { get; set; } = 0;
        private byte isGuidAvailable { get; set; } = 1;
        private readonly QQDeviceConfig config;
        public TLV0x106(QQDeviceConfig config)
        {
            this.config = config;
        }
        private byte[] getKey() => Unpooled.Buffer()
            .WriteBytes(password.ToBytes().MD5()).WriteInt(0).WriteInt((int)uin).ToArray().MD5();
        private byte[] getBody() => Unpooled.Buffer()
            .WriteShort(4)
            .WriteInt(getRandomNumber())
            .WriteInt(5)//ssoVer
            .WriteInt((int)config.appId)
            .WriteInt(config.appClientVersion)
            .WriteLong(uin == 0 ? salt : uin)
            .WriteInt(getUTCTime())
            .WriteInt(0)// ip ,no need to .Write actual ip  4bytes
            .WriteByte(1)//n5_always_1
            .WriteBytes(password.ToBytes().MD5())
            .WriteBytes(config.TgtgKey)
            .WriteInt(0)
            .WriteByte(isGuidAvailable)
            //check if the guid.size == 16
            .WriteBytes(config.GUID)
            .WriteInt((int)config.subAppId)
            .WriteInt((int)loginType)
            .WriteBytesWithLength(Unpooled.Buffer().WriteLong(uin), SHORT)
            .WriteShort(0).ToArray();
        public IByteBuffer Serialize() => QQTea.Encrypt(getBody(), getKey()).ToByteBuffer();
    }
}